package br.ufpb.di.ppgi.negocio.modelo.usuario;

import java.util.Arrays;
import java.util.Date;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Transient;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.hibernate.validator.Email;
import org.hibernate.validator.NotEmpty;
import org.hibernate.validator.NotNull;

import br.ufpb.di.ppgi.negocio.modelo.contato.InternetIdentity;
import br.ufpb.di.ppgi.negocio.servicos.login.Credencial;
import br.ufpb.di.ppgi.persistencia.listeners.UsuarioListener;
import br.ufpb.di.ppgi.util.security.Criptografia;

@Entity
@EntityListeners(UsuarioListener.class)
public class Usuario implements IUsuario {
	private static final long serialVersionUID = 7799827964349185713L;
	private Long id;
	private String email;
	private String emailPessoal;
	private String matriculaSiape;
	private String senha;
	private String nome;
	private String cpf;
	private UsuarioRole role;
	private Date dataDeCadastro;
	private Date dataDeAtualizacao;
	private boolean ativo;

	public Usuario() {}
	
	public Usuario(String login, String senha) {
		this.email = login;
		this.senha = senha;
	}
	
	@Id
	@GeneratedValue
	@Override
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	
	@Column(unique=true)
	@NotEmpty
	@Email
	@Override
	public String getEmail() {
		return email;
	}
	public void setEmail(String login) {
		this.email = login;
	}
	
	@Email
	public String getEmailPessoal() {
		return emailPessoal;
	}
	public void setEmailPessoal(String login) {
		this.emailPessoal = login;
	}
	
	public String getMatriculaSiape() {
		return matriculaSiape;
	}

	public void setMatriculaSiape(String matriculaSiape) {
		this.matriculaSiape = matriculaSiape;
	}

	@NotNull
	public String getSenha() {
		return senha;
	}

	@Transient
	public void setSenhaDescriptografada(String senha) {
		setSenha(senha != null && !senha.isEmpty() ? Criptografia.md5Encode(senha) : null);
	}
	public void setSenha(String senha) {
		this.senha = senha;
	}

	@NotNull
	public String getNome() {
		return nome;
	}
	public void setNome(String nome) {
		this.nome = nome;
	}
	@Column(unique=true,nullable=false)
	public String getCpf() {
		return cpf;
	}
	public void setCpf(String cpf) {
		this.cpf = cpf;
	}
	@NotNull
	public UsuarioRole getRole() {
		return role;
	}
	public void setRole(UsuarioRole role) {
		this.role = role;
	}
	public Date getDataDeCadastro() {
		return dataDeCadastro;
	}
	public void setDataDeCadastro(Date dataDeCadastro) {
		this.dataDeCadastro = dataDeCadastro;
	}
	public Date getDataDeAtualizacao() {
		return dataDeAtualizacao;
	}
	public void setDataDeAtualizacao(Date dataDeAtualizacao) {
		this.dataDeAtualizacao = dataDeAtualizacao;
	}
	public boolean isAtivo() {
		return ativo;
	}
	public void setAtivo(boolean ativo) {
		this.ativo = ativo;
	}
	
    public boolean equals(Object other) {
        if (other == this) return true;
        if (getId() == null && getCpf() == null)
        	return false;
        if (!(other instanceof Usuario)) return false;
        
        Usuario o = (Usuario)other;
        
        EqualsBuilder eq = new EqualsBuilder();
        
    	if (getId() != null && o.getId() != null) 
    		return eq.append(getId(), o.getId()).isEquals();
        	
    	return eq.append(getCpf(), o.getCpf()).isEquals();
    }
    
    
    public int hashCode() {
    	if (getId() == null && getCpf() == null) return super.hashCode();
    	
        HashCodeBuilder hash = new HashCodeBuilder(5,11);
        return getId() == null ? 
        		hash.append(getCpf()).toHashCode() : 
        		hash.append(getId()).toHashCode();
    }

	/*
	@Override
	public int hashCode() {
		if (getEmail() == null)
			return super.hashCode();
		final int prime = 47;
		int result = 1;
		result = prime * result + getEmail().hashCode();
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (getEmail() == null)
			return false;
		if (!(obj instanceof Usuario))
			return false;
		Usuario other = (Usuario) obj;
		
		return getEmail().equals(other.getEmail());
	}
	*/
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
			builder.append(email);
			builder.append("' [");
			builder.append(getRole());
			builder.append("]");
		return builder.toString();
	}
	
	@Override
	public boolean confirmaSenha(String senha) {
		return confirmaSenha(Criptografia.md5Encode(senha));
	}

	@Override
	public boolean confirmaSenha(Credencial credencial) {
		return this.senha.equals(credencial.getHashedPassword());
	}

	@Transient
	public InternetIdentity getInfoContato() {
		return new InternetIdentity(email,nome);
	}

	@Transient
	@Override
	public Set<String> getRoles() {
		return UsuarioRole.fetchSubRoles(role);
	}
	
	@Transient
	@Override
	public String getRolesString() {
		return Arrays.toString( getRoles().toArray() );
	}

	
}
